import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface UserInfo {
  id: string
  username: string
  email: string
  avatar?: string
  nickname?: string
  phone?: string
  company?: string
  role: 'admin' | 'user' | 'guest'
  permissions: string[]
  lastLoginTime?: string
  createdAt?: string
}

export interface LoginForm {
  username: string
  password: string
  remember?: boolean
}

export interface RegisterForm {
  username: string
  email: string
  password: string
  confirmPassword: string
  phone?: string
  company?: string
  agreeTerms: boolean
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref<UserInfo | null>(null)
  const token = ref<string>('')
  const refreshToken = ref<string>('')
  const isLoggedIn = ref(false)
  const loginLoading = ref(false)
  const registerLoading = ref(false)
  
  // 计算属性
  const isAdmin = computed(() => userInfo.value?.role === 'admin')
  const isGuest = computed(() => userInfo.value?.role === 'guest' || !userInfo.value)
  const hasPermission = computed(() => (permission: string) => {
    return userInfo.value?.permissions.includes(permission) || false
  })
  const userDisplayName = computed(() => {
    return userInfo.value?.nickname || userInfo.value?.username || '未知用户'
  })
  
  // 方法
  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
    localStorage.setItem('user-info', JSON.stringify(info))
  }
  
  const setToken = (newToken: string, newRefreshToken?: string) => {
    token.value = newToken
    localStorage.setItem('access-token', newToken)
    
    if (newRefreshToken) {
      refreshToken.value = newRefreshToken
      localStorage.setItem('refresh-token', newRefreshToken)
    }
  }
  
  const setLoginStatus = (status: boolean) => {
    isLoggedIn.value = status
    localStorage.setItem('is-logged-in', status.toString())
  }
  
  // 登录
  const login = async (loginForm: LoginForm): Promise<boolean> => {
    try {
      loginLoading.value = true
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 模拟登录成功
      const mockUserInfo: UserInfo = {
        id: '1',
        username: loginForm.username,
        email: `${loginForm.username}@example.com`,
        avatar: '/avatar-default.png',
        nickname: loginForm.username,
        role: 'user',
        permissions: ['read', 'write'],
        lastLoginTime: new Date().toISOString(),
        createdAt: '2024-01-01T00:00:00.000Z'
      }
      
      const mockToken = 'mock-jwt-token-' + Date.now()
      const mockRefreshToken = 'mock-refresh-token-' + Date.now()
      
      setUserInfo(mockUserInfo)
      setToken(mockToken, mockRefreshToken)
      setLoginStatus(true)
      
      return true
    } catch (error) {
      console.error('Login failed:', error)
      return false
    } finally {
      loginLoading.value = false
    }
  }
  
  // 注册
  const register = async (registerForm: RegisterForm): Promise<boolean> => {
    try {
      registerLoading.value = true
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1500))
      
      // 模拟注册成功
      const mockUserInfo: UserInfo = {
        id: Date.now().toString(),
        username: registerForm.username,
        email: registerForm.email,
        phone: registerForm.phone,
        company: registerForm.company,
        role: 'user',
        permissions: ['read'],
        createdAt: new Date().toISOString()
      }
      
      setUserInfo(mockUserInfo)
      
      return true
    } catch (error) {
      console.error('Register failed:', error)
      return false
    } finally {
      registerLoading.value = false
    }
  }
  
  // 登出
  const logout = async (): Promise<void> => {
    try {
      // 可以调用API通知服务器登出
      // await api.logout()
      
      // 清除本地状态
      userInfo.value = null
      token.value = ''
      refreshToken.value = ''
      setLoginStatus(false)
      
      // 清除localStorage
      localStorage.removeItem('user-info')
      localStorage.removeItem('access-token')
      localStorage.removeItem('refresh-token')
      localStorage.removeItem('is-logged-in')
    } catch (error) {
      console.error('Logout failed:', error)
    }
  }
  
  // 刷新token
  const refreshAccessToken = async (): Promise<boolean> => {
    try {
      if (!refreshToken.value) {
        return false
      }
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))
      
      const newToken = 'refreshed-token-' + Date.now()
      setToken(newToken)
      
      return true
    } catch (error) {
      console.error('Token refresh failed:', error)
      // 刷新失败，需要重新登录
      await logout()
      return false
    }
  }
  
  // 更新用户信息
  const updateUserInfo = async (updates: Partial<UserInfo>): Promise<boolean> => {
    try {
      if (!userInfo.value) {
        return false
      }
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 800))
      
      const updatedInfo = { ...userInfo.value, ...updates }
      setUserInfo(updatedInfo)
      
      return true
    } catch (error) {
      console.error('Update user info failed:', error)
      return false
    }
  }
  
  // 修改密码
  const changePassword = async (oldPassword: string, newPassword: string): Promise<boolean> => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 模拟密码修改成功
      return true
    } catch (error) {
      console.error('Change password failed:', error)
      return false
    }
  }
  
  // 检查权限
  const checkPermission = (permission: string): boolean => {
    return userInfo.value?.permissions.includes(permission) || false
  }
  
  // 检查多个权限（需要全部满足）
  const checkPermissions = (permissions: string[]): boolean => {
    return permissions.every(permission => checkPermission(permission))
  }
  
  // 检查任一权限（满足其中一个即可）
  const checkAnyPermission = (permissions: string[]): boolean => {
    return permissions.some(permission => checkPermission(permission))
  }
  
  // 初始化用户状态
  const initializeUser = () => {
    try {
      // 从localStorage恢复用户信息
      const savedUserInfo = localStorage.getItem('user-info')
      const savedToken = localStorage.getItem('access-token')
      const savedRefreshToken = localStorage.getItem('refresh-token')
      const savedLoginStatus = localStorage.getItem('is-logged-in')
      
      if (savedUserInfo && savedToken) {
        userInfo.value = JSON.parse(savedUserInfo)
        token.value = savedToken
        refreshToken.value = savedRefreshToken || ''
        isLoggedIn.value = savedLoginStatus === 'true'
      }
    } catch (error) {
      console.error('Initialize user failed:', error)
      // 清除可能损坏的数据
      logout()
    }
  }
  
  // 重置用户状态
  const resetUser = () => {
    userInfo.value = null
    token.value = ''
    refreshToken.value = ''
    isLoggedIn.value = false
    loginLoading.value = false
    registerLoading.value = false
  }
  
  return {
    // 状态
    userInfo,
    token,
    refreshToken,
    isLoggedIn,
    loginLoading,
    registerLoading,
    
    // 计算属性
    isAdmin,
    isGuest,
    hasPermission,
    userDisplayName,
    
    // 方法
    setUserInfo,
    setToken,
    setLoginStatus,
    login,
    register,
    logout,
    refreshAccessToken,
    updateUserInfo,
    changePassword,
    checkPermission,
    checkPermissions,
    checkAnyPermission,
    initializeUser,
    resetUser
  }
})